<template>
    <div class="vertificatePage">
        <input
            v-model="form.email"
            placeholder="请输入邮箱号"
            placeholder-class="account-holder"
            class="phone"
        />
        <div class="vertificate-box">
            <input
                v-model="form.code"
                placeholder="请输入验证码"
                placeholder-class="password-holder"
                @input=""
                class="vertificate"
            />
            <span class="code" @click="sendCode" :disabled="isCounting">{{ countDown > 0 ? `${countDown}s` : '发送验证码' }}</span>
        </div>
        <div class="func-box">
            <el-checkbox v-model="remember" label="记住我" size="small" />
            <div class="forget">忘记密码?</div>
        </div>
        <el-button color="#5784FF" class="button" @click="logIn">登录</el-button>
        <div class="register">
            <div>没有账户?</div>
            <div style="color: #5784FF;">立即注册</div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reqCodeCheck, reqGetCode } from '@/apis/login'
import router from '@/router'
import { useLoginStore } from '@/stores/login'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
const loginStore = useLoginStore()
let form = ref({
    email: '',
    code: ''
})
let remember = ref(false)
let countDown = ref(0)
let isCounting = ref(false)
const codeCheck = ref('')

async function sendCode() {
    if (isCounting.value) return
    try {
        let res = await reqGetCode(form.value.email)
        console.log('code',res)
        codeCheck.value = res.code
        countDown.value = 60
        isCounting.value = true
        const timer = setInterval(() => {
            if (countDown.value > 0) {
                countDown.value--
            } else {
                clearInterval(timer)
                isCounting.value = false
            }
        }, 1000)
        ElMessage.success('验证码已发送，请查收')
    } catch (error) {
        ElMessage.error('验证码发送失败，请重试')
    }
}

async function logIn() {
    const { email, code } = form.value
    if (email === '') {
        ElMessage.error('邮箱号不能为空!')
        return
    }
    if (code === '') {
        ElMessage.error('验证码不能为空!')
        return
    }
    try {
        if(form.value.code === codeCheck.value){
          loginStore.login()
          router.push('/')
        }
    } catch (error) {
        ElMessage.error('验证码验证失败!请重试')
    }
}
</script>

<style scoped lang="less">
@import url('@/views/login/vertificationView/index.less');
.code[disabled] {
    color: #999;
    cursor: not-allowed;
}
</style>